//////////////////////////////////////////////////////////////////////////////////////////////////
// Global Variable
var gSessionId;
var gSurveryorInfo;
var gClaimInfoList;
var gClaimDetail;
var gLattitude;
var gLongitude;
var gLocation;
var gUploadImageUrl;
var gCurrentClaimId = 73;
var gCaptureCarImage = true;
var gClaimDocUrl = "images/captureimage.png";
var gCaptureImageList = Array();
var gTempImageList;
var gClaimDocId;
var markers;


// ///////////////////////////////////////////////////////////////////////////////////////////////

function wlCommonInit() {

	/*
	 * Application is started in offline mode as defined by a connectOnStartup
	 * property in initOptions.js file. In order to begin communicating with
	 * Worklight Server you need to either:
	 * 
	 * 1. Change connectOnStartup property in initOptions.js to true. This will
	 * make Worklight framework automatically attempt to connect to Worklight
	 * Server as a part of application start-up. Keep in mind - this may
	 * increase application start-up time.
	 * 
	 * 2. Use WL.Client.connect() API once connectivity to a Worklight Server is
	 * required. This API needs to be called only once, before any other
	 * WL.Client methods that communicate with the Worklight Server. Don't
	 * forget to specify and implement onSuccess and onFailure callback
	 * functions for WL.Client.connect(), e.g:
	 * 
	 * WL.Client.connect({ onSuccess: onConnectSuccess, onFailure:
	 * onConnectFailure });
	 * 
	 */
	// initialization code for button click
	console.log('-wlCommonInit : Start up');
	$('#loginBtn').bind('click', callAuthenSurveyor); // call Adapter when clicked
	$('#statusBtnInfo').bind('change', getCurrentLocation);
	
	$('#acceptBtnPreview').bind('click', callSendAcceptMessage);
	$('#denyBtnPreview').bind('click', function() {
		$.mobile.changePage("#denyJobPage", {
		    transition: "slide",
		    reverse: false
		});
	});
	
	$('#denyBtn').bind('click', callSendDenyMessage);
	
	$('#carImageBtn').bind('click', function() {
		if(!gCaptureCarImage){
			gCaptureCarImage = true;
			$('#carImage').attr('style', "border:2px solid red");
			$('#claimDocImageBtn').attr('style', "border:0px");
		}else{
			/*$.mobile.changePage("#viewCarImagePage", {
			    transition: "slide",
			    reverse: true
			});*/
			$.mobile.changePage("#viewCarImagePage", {transition: "none"});
		}
	});
	
	// { transition: "none"}
    $('#takePhotoBtn').bind('click', function() {
		$.mobile.changePage("#captureImagePage", { transition: "none"});
		takePhoto();
	});
	
    $('#claimDocImageBtn').bind('click', function() {
    	if(gCaptureCarImage){
			gCaptureCarImage = false;
			$('#claimDocImageBtn').attr('style', "border:2px solid red");
			$('#carImage').attr('style', "border:0px");
		}else{
			// $.mobile.changePage("#viewClaimDocPage", "slide", false, false);
			/*$.mobile.changePage("#viewClaimDocPage", {
			    transition: "slide",
			    reverse: false
			});*/
			$.mobile.changePage("#viewClaimDocPage", {transition: "none"});
		}
	});
        
    $('#customerTelephoeBtn').bind('click', makeCustomerCall);
    $('#sendClaimDocBtn').bind('click', uploadPhoto);
	//$('#takePhotoBtn').bind('click', takePhoto); // call to take photo
	//$('#syncBtn').bind('click', callGetAllClaimInfoForCustomer); // call to
																	// take
																	// photo
	//$(document).on("click", ".claimInfoItem", function() {
	//	viewClaimDetail($(this).attr("id"));
	//});

	//$('#sendRequest').bind('click', uploadPhoto); // call to send claim
													// request
	//$('#cancelRequest').bind('click', cancelClaimRequest); // call to send
															// claim request

	if (WL.Client.Push){
	  	
	  	WL.Client.Push.onReadyToSubscribe = function(){
	  		//alert("onReadyToSubscribe");
	  		WL.Client.Push.registerEventSourceCallback(
	  				"JobIncomePush", 
	  				"PushAdapter", 
	  				"PushEventSource", 
	  				JobIncomePushNotificationReceived);

	  	};
	  	
	  }
	

	getCurrentLocationMap();
	$('#LocationBtn').bind('click',function(){
		$.mobile.changePage("#map-page", { transition: "none"});
	});
}

// initialization code for opening page
// 1. surveyorInfoPage
$(document).on(
		'pagebeforeshow',
		'#surveyorInfoPage',
		function(event) {
			console.log(' surveyorInfoPage - pagebeforeshow');
			$('#surveyorImageInfo').attr('src', gSurveryorInfo.Picture);
			//$('#carImageInfo').src = gSurveryorInfo.PicturePath;
			$('#survayorIdInfo').val(gSurveryorInfo.SurveyerId);
			$('#nameInfo').val(gSurveryorInfo.Name + " " + gSurveryorInfo.Surname);
			$('#mobileInfo').val(gSurveryorInfo.Mobile);
		});

// 2. jobPreviewPage
$(document).on(
		'pagebeforeshow',
		'#jobPreviewPage',
		function(event) {
			console.log(' jobPreviewPage - pagebeforeshow');
			callGetClaimInfoForSurveyor();
		});

// 3. claimListPage
$(document).on('pagebeforeshow', '#claimListPage', function(event) {
	console.log(' claimListPage - pagebeforeshow');

	//if (typeof (gClaimInfoList) == 'undefined' || gClaimInfoList == null) {
		// call adapter to load data
		callGetAllClaimInfoForCustomer();
	//} else {
	//	refreshClaimListView();
	//}
});

// 4. jobDetailPage
$(document).on('pagebeforeshow', '#jobDetailPage', function(event) {
	console.log(' jobDetailPage - pagebeforeshow');
	
	if(gClaimDetail==null){
		return;
	}
	
	var dateStr = getFormatJsonDate(gClaimDetail.AccidentDate);
	
	$('#carImageDetail').attr('src', gClaimDetail.CarImage);
	$('#licenseplateDetail').val(gClaimDetail.LicensePlate);
	$('#customernameDetail').val(gClaimDetail.CustName);
	$('#cardetailDetail').val(gClaimDetail.CarDetail);
	$('#customermobileDetail').val(gClaimDetail.CustMobile);
	$('#accDateDetail').val(dateStr);
	$('#accLocationDetail').val(gClaimDetail.AccidentLocation);
});

//5. claimMapPage
$(document).on('pageshow', '[data-role="page"]#map-page', function(event) {
	console.log(' map-page - pagebeforeshow');
	var iconAccident = new google.maps.MarkerImage("images/accident.png");
	var iconSurveyor = new google.maps.MarkerImage("images/motorcycle.png");
	 markers = [
	               {
	                   "title": 'Accident',
	                   "lat": gLatitude,
	                   "lng": gLongitude,
	                   "description": 'Surveyor',
		               icon: iconSurveyor
	               },
	               {
	                   "title": 'Surveyor',
	                   "lat": gClaimDetail.AccidentLatitude,
	                   "lng": gClaimDetail.AccidentLongitude,
	                   "description": 'Accident',
	                   icon: iconAccident
	               }
	       ];
//	 markers = [
// {
//     "title": 'Alibaug',
//     "lat": '18.641400',
//     "lng": '72.872200',
//     "description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
// }
//,
// {
//     "title": 'Mumbai',
//     "lat": '18.964700',
//     "lng": '72.825800',
//     "description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
// }
//];

		wlMapDrawPolyline(markers);
});
//5. viewCarImagePage
/*$(document).on('pagebeforeshow', '#viewCarImagePage', function(event) {
	console.log(' viewCarImagePage - pagebeforeshow');
	gCaptureImageList.push('images/001.jpg');
	gCaptureImageList.push('images/003.jpg');
	gCaptureImageList.push('images/006.jpg');
	
	var data = gCaptureImageList;
	
	$('#Gallery').empty();
	for (var i = 0; i < data.length; i++) {
		var url = data[i];		
		var item = $('<ul data-role="listview" data-inset="true">'+
					 '<li><a href="#">' +
					 '<img src="' +
					 url +
					 '" class="ui-li-thumb">' +					 
					 '</a></li>' +
					 '</ul>');
		
		$("#Gallery").append(item);
	}
	
	var myPhotoSwipe = $("#Gallery a").photoSwipe({
        jQueryMobile: true,
        loop: true,
        enableMouseWheel: true,
        enableKeyboard: false
    });
       
    myPhotoSwipe.show(0);
});*/

$(document).on('pagebeforeshow', '#viewCarImagePage', function(event) {
	console.log(' viewCarImagePage - pagebeforeshow');
	//gCaptureImageList.push('images/001.jpg');
	//gCaptureImageList.push('images/003.jpg');
	//gCaptureImageList.push('images/006.jpg');
	var tempImageList = Array();
	tempImageList.push('images/captureimage.png');
	console.log('* tempImageList length = ' + tempImageList.length);
	
	var data = gCaptureImageList;
	if(data.length<=0){
		console.log(' add temp image');
		data = tempImageList;
	}
	
	console.log('num image : ' + data.length);
	$('#Gallery').empty();
	for (var i = 0; i < data.length; i++) {
		var url = data[i];
		var item = $('<a href="' + 
					  url +
				      '"><img src="' +
				      url +
				      '" alt="Image" width="150" /></a>'
				     );
		$("#Gallery").append(item);
	}
	
	var myPhotoSwipe = $("#Gallery a").photoSwipe({
        jQueryMobile: true,
        loop: true,
        enableMouseWheel: true,
        enableKeyboard: false
    });
       
    myPhotoSwipe.show(0);
});

$(document).on('pagebeforeshow', '#viewClaimDocPage', function(event) {
	console.log(' viewClaimDocPage - pagebeforeshow');
	$('#claimDocImageView').attr('src', gClaimDocUrl);
});


/*$(document).on('pagebeforeshow', '#viewCarImagePage', function(event) {
	console.log(' viewCarImagePage - pagebeforeshow');
	gCaptureImageList.push('images/001.jpg');
	gCaptureImageList.push('images/003.jpg');
	gCaptureImageList.push('images/006.jpg');
	
	var data = gCaptureImageList;
	
	$('#Gallery').empty();
	for (var i = 0; i < data.length; i++) {
		var url = data[i];
		var item = $('<div class="gallery-item"><a href="' + 
					  url +
				      '"><img src="' +
				      url +
				      '" alt="Image" width="60" /></a></div>'
				     );
		$("#Gallery").append(item);
	}
	
	var myPhotoSwipe = $("#Gallery a").photoSwipe({
        jQueryMobile: true,
        loop: true,
        enableMouseWheel: true,
        enableKeyboard: false
    });
       
    myPhotoSwipe.show(0);
});*/

// ///////////////////////////////////////////////////////////////////////////////////////////////
// Adapter Handler
// ///////////////////////////////////////////////////////////////////////////////////////////////
function makeCustomerCall() {
	console.log(' makeCall - begin');
	//window.open("tel:" + gClaimDetail.CustMobile);
	// window.open("tel:0858056696"); iOS
	window.open('tel:'+ gClaimDetail.CustMobile, '_system', 'location=yes');
	console.log(' makeCall - end');
}

// ///////////////////////////////////////////////////////////////////////////////////////////////
// 1. callAuthenSurveyor
function callAuthenSurveyor() {
	$.mobile.showPageLoadingMsg();
	console.log('-callAuthenSurveyor : begin');

	var username = $('#surveyorIdInp').val();
	var password = $('#passwordInp').val();
	if (!username || username.length === 0 || !password || password.lenght === 0) {
		$.mobile.hidePageLoadingMsg();
		alert("Error : empty usename or password");
		/*navigator.notification.alert('empty license plate or password!', // message
		null, // callback
		'Error', // title
		'OK' // buttonName
		);
		navigator.notification.beep(1);*/
		return;
	}
	
	var authenSurveyorDto = new Object();
	authenSurveyorDto.Username = username;
	authenSurveyorDto.Password = password;
	authenSurveyorDto.NoSurveyorData = true;
	authenSurveyorDto.RegistrationId = 'APA91bG1hM8_uSVEuvhYPoMRQ1434j8QSMV6UOgb00OiWrGJAshJkOZ9oimSJ-2-lbapjme8jkTgLCCrOJ6FWqj7Cb981K83UPrShei54xvDNW-LKT6Pv-unlbdWhu0j5T3yvLwXKF36x9cH-Z3rWMnrNyeiUEHN7Q';

	var callSuccess = function(result) {
		subscribe();
		$.mobile.hidePageLoadingMsg();
		var invocationResult = result.invocationResult;
		console.log('-callAuthenSurveyor : Success');

		if (!invocationResult.Result) {
			alert("Invalid username or password");
			/*navigator.notification.alert(invocationResult.ErrorMsg, // message
			null, // callback
			'Error', // title
			'OK' // buttonName
			);
			return;*/
		}
		//alert(invocationResult.SessionId);
		
		// keep data to global space
		gSessionId = invocationResult.SessionId;
		gSurveryorInfo = invocationResult.SurveyorInfo;
		$.mobile.changePage("#surveyorInfoPage", { transition: "none"});
		return;
	};

	var callFailure = function() {
		$.mobile.hidePageLoadingMsg();
		alert("callFailure");
		console.log('-callAuthenSurveyor : Failed');
		return;
	};

	var invocationData = {
		adapter : 'EasyClaimBL',
		procedure : 'AuthenSurveyor',
		parameters : [ authenSurveyorDto ]
	};

	var options = {
		onSuccess : callSuccess,
		onFailure : callFailure
	};

	WL.Client.invokeProcedure(invocationData, options);
}

/////////////////////////////////////////////////////////////////////////////////////////////////
// 2. callUpdateSurveyorStatus
function callUpdateSurveyorStatus() {
	$.mobile.showPageLoadingMsg();
	console.log('-callUpdateSurveyorStatus : begin');
	//alert('-callUpdateSurveyorStatus : begin');
	if (gSessionId.length <= 0) {
		$.mobile.hidePageLoadingMsg();
		alert("Error : empty session id");
		/*navigator.notification.alert('empty session id', // message
			null, // callback
			'Error', // title
			'OK' // buttonName
		);
		navigator.notification.beep(1);*/
		return;
	}
	
	var status = $('#statusBtnInfo').val();
	
	var surveyorStatusDto = new Object();
	surveyorStatusDto.SessionId = gSessionId;
	surveyorStatusDto.Status = status;
	surveyorStatusDto.Latitude = gLattitude;
	surveyorStatusDto.Longitude = gLongitude;
	
	var callSuccess = function(result) {
		$.mobile.hidePageLoadingMsg();
		var invocationResult = result.invocationResult;
		console.log('-UpdateSurveyorStatus  : Success');
		//alert('-callUpdateSurveyorStatus : Success');

		if (!invocationResult.Result) {
			alert("callUpdateSurveyorStatus result fail");
			/*navigator.notification.alert(invocationResult.ErrorMsg, // message
			null, // callback
			'Error', // title
			'OK' // buttonName
			);*/
			return;
		}
		//alert('callUpdateSurveyorStatus success');

		return;
	};

	var callFailure = function() {
		$.mobile.hidePageLoadingMsg();
		alert("call UpdateSurveyorStatus Failure");
		console.log('-callUpdateSurveyorStatus : Failed');
		return;
	};

	var invocationData = {
		adapter : 'EasyClaimBL',
		procedure : 'UpdateSurveyorStatus',
		parameters : [ surveyorStatusDto ]
	};

	var options = {
		onSuccess : callSuccess,
		onFailure : callFailure
	};

	WL.Client.invokeProcedure(invocationData, options);
	//alert('-callUpdateSurveyorStatus : end');
}

/////////////////////////////////////////////////////////////////////////////////////////////////
// 3. callGetClaimInfoForSurveyor
function callGetClaimInfoForSurveyor() {
	$.mobile.showPageLoadingMsg();
	console.log('-callGetClaimInfoForSurveyor : begin');

	if (gSessionId.length <= 0) {
		$.mobile.hidePageLoadingMsg();
		alert("Error : empty session id");
		/*navigator.notification.alert('empty session id', // message
			null, // callback
			'Error', // title
			'OK' // buttonName
		);
		navigator.notification.beep(1);*/
		return;
	}
		
	var claimInfoPKDto = new Object();
	claimInfoPKDto.SessionId = gSessionId;
	claimInfoPKDto.Id = gCurrentClaimId;
	
	var callSuccess = function(result) {
		$.mobile.hidePageLoadingMsg();
		var invocationResult = result.invocationResult;
		console.log('-callGetClaimInfoForSurveyor  : Success');

		if (invocationResult.LicensePlate.length <=0) {
			alert("callGetClaimInfoForSurveyor result fail");
			/*navigator.notification.alert('Call GetClaimInfoForSurveyor Fail', // message
			null, // callback
			'Error', // title
			'OK' // buttonName
			);*/
			return;
		}
		gClaimDetail = new Object();
		gClaimDetail.LicensePlate = invocationResult.LicensePlate;
		gClaimDetail.CustName = invocationResult.CustName;
		gClaimDetail.CarDetail = invocationResult.CarDetail;
		gClaimDetail.CustMobile = invocationResult.CustMobile;
		gClaimDetail.CarImage = invocationResult.CarImage;
		gClaimDetail.AccidentDate = invocationResult.AccidentDate;
		gClaimDetail.AccidentLocation = invocationResult.AccidentLocation;
		gClaimDetail.AccidentLatitude = invocationResult.AccidentLatitude;
		gClaimDetail.AccidentLongitude = invocationResult.AccidentLongitude;
		
		
		var dateStr = getFormatJsonDate(gClaimDetail.AccidentDate);
		
		$('#carImagePreview').attr('src', gClaimDetail.CarImage);
		$('#licenseplatePreview').val(gClaimDetail.LicensePlate);
		$('#customernamePreview').val(gClaimDetail.CustName);
		$('#cardetailPreview').val(gClaimDetail.CarDetail);
		$('#customermobilePreview').val(gClaimDetail.CustMobile);
		$('#accDatePreview').val(dateStr);
		$('#accLocationPreview').val(gClaimDetail.AccidentLocation);
		
		return;
	};

	var callFailure = function() {
		$.mobile.hidePageLoadingMsg();
		alert("call UpdateSurveyorStatus Failure");
		console.log('-callUpdateSurveyorStatus : Failed');
		return;
	};

	var invocationData = {
		adapter : 'EasyClaimBL',
		procedure : 'GetClaimInfoForSurveyor',
		parameters : [ claimInfoPKDto ]
	};

	var options = {
		onSuccess : callSuccess,
		onFailure : callFailure
	};

	WL.Client.invokeProcedure(invocationData, options);
}

/////////////////////////////////////////////////////////////////////////////////////////////////
// 4. callSendAcceptMessage
function callSendAcceptMessage() {
	$.mobile.showPageLoadingMsg();
	console.log('-callSendAcceptMessage : begin');

	if (gSessionId.length <= 0) {
		$.mobile.hidePageLoadingMsg();
		// alert("Error : empty session id");
		navigator.notification.alert('empty session id', // message
			null, // callback
			'Error', // title
			'OK' // buttonName
		);
		navigator.notification.beep(1);
		return;
	}
		
	var acceptMessageBlDto = new Object();
	acceptMessageBlDto.sessionId = gSessionId;
	acceptMessageBlDto.ClaimId = gCurrentClaimId;

	var callSuccess = function(result) {
		$.mobile.hidePageLoadingMsg();
		var invocationResult = result.invocationResult;
		
		//alert("callSendAcceptMessage result");
		if (!invocationResult.Result) {
			$.mobile.hidePageLoadingMsg();
			alert("Error : call callSendAcceptMessage result failed : " + invocationResult.ErrorMsg);
			/*navigator.notification.alert(invocationResult.ErrorMsg, // message
			null, // callback
			'Error', // title
			'OK' // buttonName
			);*/
			return;
		}

		//alert("callSendAcceptMessage success");
		console.log('-callSendAcceptMessage  : Success');
		$.mobile.changePage("#jobDetailPage", { transition: "none"});
		
		callUpdateSurveyorLocation();
		return;
	};

	var callFailure = function() {
		$.mobile.hidePageLoadingMsg();
		alert("call callSendAcceptMessage Failure");
		console.log('-callSendAcceptMessage : Failed');
		return;
	};

	var invocationData = {
		adapter : 'EasyClaimBL',
		procedure : 'SendAcceptMessage',
		parameters : [ acceptMessageBlDto ]
	};

	var options = {
		onSuccess : callSuccess,
		onFailure : callFailure
	};

	WL.Client.invokeProcedure(invocationData, options);
}

/////////////////////////////////////////////////////////////////////////////////////////////////
// 5. callSendDenyMessage
function callSendDenyMessage() {
	$.mobile.showPageLoadingMsg();
	console.log('-callSendDenyMessage : begin');

	if (gSessionId.length <= 0) {
		$.mobile.hidePageLoadingMsg();
		alert("Error : empty session id");
		/*navigator.notification.alert('empty session id', // message
			null, // callback
			'Error', // title
			'OK' // buttonName
		);
		navigator.notification.beep(1);*/
		return;
	}
	
	console.log('gSessionId = ' + gSessionId + 'gCurrentClaimId = ',gCurrentClaimId);
	var denyMessageDto = new Object();
	denyMessageDto.SessionId = gSessionId;
	denyMessageDto.ClaimId = gCurrentClaimId;
	denyMessageDto.DenyReason = $('#resonDeny').val();
	
	var callSuccess = function(result) {
		$.mobile.hidePageLoadingMsg();
		var invocationResult = result.invocationResult;
		console.log('-callSendDenyMessage  : Success');

		if (!invocationResult.Result) {
			alert("Error : call callSendAcceptMessage result failed : " + invocationResult.ErrorMsg);
			/*navigator.notification.alert(invocationResult.ErrorMsg, // message
			null, // callback
			'Error', // title
			'OK' // buttonName
			);*/
			return;
		}
		//alert('callSendDenyMessage success');
		$.mobile.changePage("#surveyorInfoPage", { transition: "none"});
		return;
	};

	var callFailure = function() {
		$.mobile.hidePageLoadingMsg();
		alert("call callSendDenyMessage Failure");
		console.log('-callSendDenyMessage : Failed');
		return;
	};

	var invocationData = {
		adapter : 'EasyClaimBL',
		procedure : 'SendDenyMessage',
		parameters : [ denyMessageDto ]
	};

	var options = {
		onSuccess : callSuccess,
		onFailure : callFailure
	};

	WL.Client.invokeProcedure(invocationData, options);
}

/////////////////////////////////////////////////////////////////////////////////////////////////
// 6. UpdateClaim
function callUpdateClaim() {
	$.mobile.showPageLoadingMsg();
	console.log('-callUpdateClaim : begin');

	if (gSessionId.length <= 0) {
		$.mobile.hidePageLoadingMsg();
		alert("Error : empty session id");
		/*navigator.notification.alert('empty session id', // message
			null, // callback
			'Error', // title
			'OK' // buttonName
		);
		navigator.notification.beep(1);*/
		return;
	}
	
	var updateClaimInfoDto = new Object();
	updateClaimInfoDto.SessionId = gSessionId;
	updateClaimInfoDto.ClaimId = gCurrentClaimId;
	updateClaimInfoDto.ClaimDocImage = gUploadImageUrl;

	var callSuccess = function(result) {
		$.mobile.hidePageLoadingMsg();
		var invocationResult = result.invocationResult;
		console.log('-callUpdateClaim : Success');
		
		if(invocationResult.ClaimNumber<=0){
		//if (!invocationResult.ErrorMsg || invocationResult.ErrorMsg.length>0 ) {
		
			alert("Error : callUpdateClaim result fail");
			/*navigator.notification.alert(invocationResult.ErrorMsg, // message
			null, // callback
			'Error', // title
			'OK' // buttonName
			);*/
			return;
		}
		// keep data to global space
		gClaimDocId = invocationResult.ClaimNumber;
		var claimNo = "Claim No : " + gClaimDocId;
		$('#claimDocIdText').html(claimNo);
		return;
	};

	var callFailure = function() {
		$.mobile.hidePageLoadingMsg();
		alert("call callUpdateClaim Failure");
		console.log('-callUpdateClaim : Failed');
		return;
	};

	var invocationData = {
		adapter : 'EasyClaimBL',
		procedure : 'UpdateClaim',
		parameters : [ updateClaimInfoDto ]
	};

	var options = {
		onSuccess : callSuccess,
		onFailure : callFailure
	};

	WL.Client.invokeProcedure(invocationData, options);
}

/////////////////////////////////////////////////////////////////////////////////////////////////
// 3. callAddClaimRequest
function callAddClaimRequest() {
	$.mobile.showPageLoadingMsg();
	console.log('-callAddClaimRequest : begin');

	if (gSessionId.length <= 0) {
		$.mobile.hidePageLoadingMsg();
		// alert("Error : empty session id");
		navigator.notification.alert('empty license plate or password!', // message
		null, // callback
		'Error', // title
		'OK' // buttonName
		);
		navigator.notification.beep(1);
		return;
	}

	var claimRequestDto = new Object();
	claimRequestDto.SessionId = gSessionId;
	claimRequestDto.AccImg = gAccImageUrl;
	claimRequestDto.Latitude = gLatitude;
	claimRequestDto.Longitude = gLongitude;
	claimRequestDto.Location = gLocation;

	var callSuccess = function(result) {
		//$.mobile.hidePageLoadingMsg();
		var invocationResult = result.invocationResult;
		console.log('-callAddClaimRequest : Success');

		if (!invocationResult.Result) {
			alert("Invalid username or password");
			/*navigator.notification.alert(invocationResult.ErrorMsg, // message
			null, // callback
			'Error', // title
			'OK' // buttonName
			);*/
			return;
		}
		//alert(invocationResult.SessionId);
		
		// keep data to global space
		gCurrentClaimId = invocationResult.ClaimInfoId;
		$.mobile.changePage("#customerInfoPage", { transition: "none"});
		//callGetClaimInfoForCustomer();
		return;
	};

	var callFailure = function() {
		$.mobile.hidePageLoadingMsg();
		alert("callFailure");
		console.log('-callAddClaimRequest : Failed');
		return;
	};

	var invocationData = {
		adapter : 'EasyClaimBL',
		procedure : 'AddClaimRequest',
		parameters : [ claimRequestDto ]
	};

	var options = {
		onSuccess : callSuccess,
		onFailure : callFailure
	};

	WL.Client.invokeProcedure(invocationData, options);
}

/////////////////////////////////////////////////////////////////////////////////////////////////
// 4. callgetLocation
function callGetLocation(){

	if (typeof(gLattitude)  == 'undefined' || gLattitude  == null ||
		typeof(gLongitude) == 'undefined' || gLongitude == null ){
		return;  
	}
		
	// Called when the adapter completes successfully 
	var onGetLocationSuccess = function(result){
		var globalAddress = result.invocationResult.results[0].formatted_address;
		// alert('globalAddress[' + globalAddress.length + '] '+ globalAddress);
		if(globalAddress.length == 0){
			alert("call GetLocation result fail");
			return;
		}
		gLocation = globalAddress;
		callAddClaimRequest();
		return;
	};

	// Called when the adapter does NOT complete successfully 
	var onGetLocationFail = function(){
		console.log('-callGetLocation:lose - Failed to obtain address for GPS');		
		$.mobile.hidePageLoadingMsg();
		alert("call GetLocation fail");
		return;
	};
	
	var invocationData = {
			adapter    : 'GoogleMapBL',
		    procedure  : 'getLocation',
		    parameters : [gLattitude, gLongitude]
	};
	
	var options = {
		onSuccess : onGetLocationSuccess,
		onFailure : onGetLocationFail
	};

	WL.Client.invokeProcedure(invocationData, options);
}

/////////////////////////////////////////////////////////////////////////////////////////////////
// 5. GetClaimInfoForCustomer
function callGetClaimInfoForCustomer() {
//	$.mobile.showPageLoadingMsg();
	console.log('-callGetClaimInfoForCustomer : begin');

	if (gSessionId.length <= 0) {
		$.mobile.hidePageLoadingMsg();
		alert("Error : empty session id");
		/*navigator.notification.alert('empty license plate or password!', // message
		null, // callback
		'Error', // title
		'OK' // buttonName
		);
		navigator.notification.beep(1);*/
		return;
	}
	// alert(gSessionId);
	var claimInfoPKDto = new Object();
	claimInfoPKDto.SessionId = gSessionId;
	claimInfoPKDto.Id = gCurrentClaimId;
	
	var callSuccess = function(result) {
		$.mobile.hidePageLoadingMsg();
		var invocationResult = result.invocationResult;
		console.log('-callGetClaimInfoForCustomer : Success');

		if (!invocationResult.Result) {
			alert("Error : call not success");
			/*navigator.notification.alert(invocationResult.ErrorMsg, // message
			null, // callback
			'Error', // title
			'OK' // buttonName
			);*/
			return;
		}
		// keep data to global space
		//gClaimInfoList = invocationResult.ClaimInfoList;
		refreshClaimListView();

		return;
	};

	var callFailure = function() {
		$.mobile.hidePageLoadingMsg();
		alert("callFailure");
		console.log('-callGetClaimInfoForCustomer : Failed');
		return;
	};

	var invocationData = {
		adapter : 'EasyClaimBL',
		procedure : 'GetClaimInfoForCustomer',
		parameters : [ claimInfoPKDto ]
	};

	var options = {
		onSuccess : callSuccess,
		onFailure : callFailure
	};

	WL.Client.invokeProcedure(invocationData, options);
}


/////////////////////////////////////////////////////////////////////////////////////////////////
//5. Update Surveyor location
function callUpdateSurveyorLocation() {
//$.mobile.showPageLoadingMsg();
	console.log('-callUpdateSurveyorLocation : begin');
	
	if (gSessionId.length <= 0) {
	$.mobile.hidePageLoadingMsg();
		alert("Error : empty session id");
		/*navigator.notification.alert('empty license plate or password!', // message
		null, // callback
		'Error', // title
		'OK' // buttonName
		);
		navigator.notification.beep(1);*/
		return;
	}
	// alert(gSessionId);
	//var claimInfoPKDto = new Object();
	//claimInfoPKDto.SessionId = gSessionId;
	//claimInfoPKDto.Id = gCurrentClaimId;
	var surveyorLocationDto = new Object();
	surveyorLocationDto.SessionId = gSessionId;
	surveyorLocationDto.Status = true;
	surveyorLocationDto.Latitude= gLattitude;
	surveyorLocationDto.Longitude = gLongitude;
	
	var callSuccess = function(result) {
		return;
	};
	
	var callFailure = function() {
	return;
	};
	
	var invocationData = {
	adapter : 'EasyClaimBL',
	procedure : 'UpdateSurveyorLocation',
	parameters : [ surveyorLocationDto ]
	};
	
	var options = {
	onSuccess : callSuccess,
	onFailure : callFailure
	};
	
	WL.Client.invokeProcedure(invocationData, options);
}


/////////////////////////////////////////////////////////////////////////////////////////////////
//
function refreshClaimListView() {
	/*
	 * <li> <a href='#viewphoto' data-rel='dialog'> <img style='margin: 10px'
	 * src='' width="60px"/> <h3>Id : </h3> <p>Date :</p> <p>Status :</p>
	 * </a> <a href='#' data-rel='dialog'></a> </li>
	 */

	if (typeof (gClaimInfoList) == 'undefined' || gClaimInfoList == null) {
		// do nothing
		return;
	}

	var data = gClaimInfoList;

	$('#claimInfoListView').empty();

	for (var i = 0; i < data.length; i++) {
		var item = data[i];
		/*
		 * var listItem = $('<li>' + '<a href=\'#viewphoto\'
		 * data-rel=\'dialog\'>' + '<img style=\'margin: 10px\' src=\'\'
		 * width=\"60px\"/>' + '<h3>Id : </h3>' + '<p>Date :</p>' + '<p>Status :</p>' + '</a>' + '<a
		 * href=\'#\' data-rel=\'dialog\'></a>' + '</li>');
		 */

		// var date = new Date(parseInt(item.AccDate.match(/(\d+)/)[1],10));
		// var dateStr = date.format("m/dd/yy h:MM");
		var listItem = $('<li>'
				+ '<a data-rel=\'dialog\' class="claimInfoItem" id="' + i
				+ '">' + '<img style=\'margin: 10px\' src=\'' + item.SurvImg
				+ '\'  width="60px"/>' + '<h6>' + item.AccidentLocation
				+ '</h6>' + '<p>Date :' + item.AccDate + '</p>' + '<p>Status :'
				+ item.Status + '</p>' + '</a>' +
				// '<a href=\'#\' data-rel=\'dialog\'></a>'+
				'</li>');
		$("#claimInfoListView").append(listItem);
	}

	$('#claimInfoListView:visible').listview('refresh');
}

// ////////////////////////////////////////////////////////////////////////////////////////////////
// 
function viewClaimDetail(id) {
	if (typeof (gClaimInfoList) != 'undefined' && gClaimInfoList != null) {
		gClaimDetail = gClaimInfoList[id];
		$.mobile.changePage("#claimDetailPage", { transition: "none"});
	}
}

// /////////////////////////////////////////////////////////////////////////////////////////////////
// send calim request page
function cancelClaimRequest() {
	var image = $('#captareImageRequest');
	image.attr('src', 'images/captureimage.png');
	//image.src = imageData;
	// image.src = image;
	image.show();
}

function takePhoto() {
	console.log("in capturePhoto()");
	// Take picture using device camera and retrieve image as base64-encoded
	// string
	//alert('Begin takePhoto');
	// navigator.camera.getPicture(onTakePhotoSuccess, onFail, {
	// quality : 10,
	// destinationType : navigator.camera.DestinationType.DATA_URL
	// });

	navigator.camera.getPicture(onTakePhotoSuccess, onTakePhotoFail, {
		quality : 50,
		destinationType : Camera.DestinationType.FILE_URI
	});
}

// success callBack.
function onTakePhotoSuccess(imageData) {
	console.log("in onPhotoDataSuccess()");
	
	var buttonImage;
	//var buttonImage2;
	var imageView;
	if(gCaptureCarImage){
		buttonImage = $('#carImage');
		//buttonImage2 = $('#carImage2');
		gCaptureImageList.push(imageData);
		imageView = $('#carImageView');
	}else{
		buttonImage = $('#claimDocImage');
		//buttonImage2 = $('#claimDocImage2');
		gClaimDocUrl = imageData;

		imageView = $('#claimDocImageView');
		
	}

	buttonImage.attr('src', imageData);
	buttonImage.show();
	
	//buttonImage2.attr('src', imageData);
	//buttonImage2.show();
		
	var captureImage = $('#captareImageRequest'); 
	captureImage.attr('src', imageData);
	captureImage.show();
	
	imageView.attr('src', imageData);
	imageView.show();
}

// failed callBack.
function onTakePhotoFail(message) {
	console.log("in onFail() - " + message);
	alert('take photo failed : ' + message);
}

function uploadPhoto() {
	//alert('Begin Upload');

	imageURI = gClaimDocUrl;
	
	var options = new FileUploadOptions();
	options.fileKey = "file";
	options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
	options.mimeType = "image/jpeg";
	
	var params = new Object();
	params.value1 = "test";
	params.value2 = "param";

	options.params = params;

	var ft = new FileTransfer();
	ft.upload(imageURI, "http://202.21.149.53/DroidClaim/UploadFile.ashx",
			onUploadSuccess, onUploadFail, options);

}

function onUploadSuccess(result) {
	var r = JSON.parse(result.response);
	
	if (!r.Result) {
		$.mobile.hidePageLoadingMsg();
		alert('Error : result from call upload is not OK');
		return;
	}

	gUploadImageUrl = r.ListFiles[0];
	callUpdateClaim();
}

function onUploadFail(error) {
	$.mobile.hidePageLoadingMsg();
	alert("An error has occurred: Code = " + error.code);
	console.log("upload error source " + error.source);
	console.log("upload error target " + error.target);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////
// Location
function getCurrentLocation() {
	$.mobile.showPageLoadingMsg();
	console.log('-getCurrentLocation : Begin');
	var status = $('#statusBtnInfo').val();
	console.log("status : " + status);
	var onLocationSuccess = function(position) {
		$.mobile.hidePageLoadingMsg();
		// alert("getCurrentLocation Success");
		console.log('-getCurrentLocation : Success');
		gLattitude = position.coords.latitude;
		gLongitude = position.coords.longitude;
		callUpdateSurveyorStatus();
		return;
	};

	var onLocationError = function(error) {
		$.mobile.hidePageLoadingMsg();
		alert('Error Code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
		console.log('-getCurrentLocation : Failed');
		return;
	};

	navigator.geolocation.getCurrentPosition(onLocationSuccess, onLocationError,{
	      enableHighAccuracy : true
	 });
}

function subscribe(){
	WL.Client.Push.subscribe("JobIncomePush", {
		onSuccess: pushSubscribe_Callback,
		onFailure: pushSubscribe_Callback
	});
}

function pushSubscribe_Callback(response){
	//alert("PushSubscribe_Callback JobIncomePush invoked");
}

//------------------------------- Handle received notification ---------------------------------------
function JobIncomePushNotificationReceived(props, payload){
	//alert("pushNotificationReceived invoked");
	//alert(payload.id);
	alert("Have a job.");
	gCurrentClaimId = payload.id;
	$.mobile.changePage("#jobPreviewPage", { transition: "none"});
}


function wlMapDrawPolyline(markers){
	var mapOptions = {
            center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
            zoom: 5,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
        var infoWindow = new google.maps.InfoWindow();
        var lat_lng = new Array();
        var latlngbounds = new google.maps.LatLngBounds();
        for (var i = 0; i < markers.length; i++) {
            var data = markers[i];
            var myLatlng = new google.maps.LatLng(data.lat, data.lng);
            lat_lng.push(myLatlng);
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: data.title, 
                icon: data.icon
            });

            latlngbounds.extend(marker.position);

            (function (marker, data) {
                google.maps.event.addListener(marker, "click", function (e) {
                    infoWindow.setContent(data.description);
                    infoWindow.open(map, marker);
                });
            })(marker, data);

        }

        map.setCenter(latlngbounds.getCenter());
        map.fitBounds(latlngbounds);

        if(markers.length < 2)
        	return;
        
        
        //***********ROUTING****************//

        //Intialize the Path Array

        var path = new google.maps.MVCArray();

        //Intialize the Direction Service

        var service = new google.maps.DirectionsService();

        //Set the Path Stroke Color

        var poly = new google.maps.Polyline({ map: map, strokeColor: '#e74976' });

        //Loop and Draw Path Route between the Points on MAP

        for (var i = 0; i < lat_lng.length; i++) {
            if ((i + 1) < lat_lng.length) {
                var src = lat_lng[i];
                var des = lat_lng[i + 1];
                path.push(src);
                poly.setPath(path);
                service.route({
                    origin: src,
                    destination: des,
                    travelMode: google.maps.DirectionsTravelMode.DRIVING
                }, function (result, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                            path.push(result.routes[0].overview_path[i]);
                        }
                    }
                });
            }
        }	
}

function getCurrentLocationMap() {

	var onLocationSuccess = function(position) {
		console.log('-getCurrentLocation : Success');
		gLatitude = position.coords.latitude;
		gLongitude = position.coords.longitude;
		//alert(gLatitude+'|'+gLongitude);
		return;
	};

	var onLocationError = function(error) {
		$.mobile.hidePageLoadingMsg();
		//* alert('Error Code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
		console.log('-getCurrentLocation : Failed');
		return;
	};
	 
	navigator.geolocation.getCurrentPosition(onLocationSuccess, onLocationError,{
	      enableHighAccuracy : true
	 });
}
///////////////////////////////////////////////////////////////////////////////////
//Utility
function getFormatJsonDate(jsonDate){
	var date = new Date(parseInt(jsonDate.slice(6, -2)));
	var dateStr;
	dateStr = (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear();
	dateStr = dateStr + " " + date.getHours() + ":" + date.getMinutes();
	
	return dateStr;
}

function getClaimStatus(code){
	var status = '';
	if(code===1){
		status = 'Claim Started';
	}else if(code===2){
		status = 'Claim Received';
	}else if(code===3){
		status = 'Surveyor Accepted';
	}else if(code===4){
		status = 'Job Handled';
	}else if(code===5){
		status = 'Got ClaimDoc Id';
	}

	return status;
}